<?php

/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\controller\adminapi\platform\app;


use app\controller\adminapi\platform\PlatformController;
use app\common\controller\AdminController;
use app\common\model\platform\PlatformApp;
use app\common\model\platform\PlatformAppOpen;
use app\common\model\platform\PlatformSetting;
use app\common\model\system\Config;
use hiduoke\services\FormBuilder as Form;
use think\App;

class MinAppSetting extends PlatformController
{
    /**
     * @var PlatformSetting
     */
    private $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new PlatformSetting();
    }


    public function index()
    {
        $data = array(
            ['label' => "服务端设置", 'key' => 'server_config'],
            ['label' => "上传设置", 'key' => 'upload'],
        );
        return $this->success('ok', $data);
    }


    /**
     * 上传配置
     * @return \think\response\Json
     */
    public function upload()
    {
        $appid = $this->request->param('appid', 0);
        $platform_app = (new PlatformApp())->where(['id' => $appid])->find();
        $plaid = $platform_app['plaid'];
        if (!$platform_app) {
            return $this->error('请先设置默认小程序');
        }

        if ($this->request->isPost()) {
            $formData = $this->request->param('formData', []);
            $res = $this->model->setValueByKey($formData, "upload", $plaid, $appid);
            return $this->success("修改成功", $res);
        } else {
            $rule = array();
            //创建表单
            $row = $this->model->getValueByKey("upload", $plaid, $appid);
            $form = Form::createForm("/adminapi/platform/min_app/setting/upload?plaid=" . $plaid . "&appid=" . $appid)->setMethod("post");
            //新增表单
            if ($platform_app['app_type'] == 'dy') {
                $rule[] = Form::input('appid', 'AppID', $row['appid'] ?? '')->effect(['help' => '在抖音开放平台-控制台-小程序-开发-开发配置-小程序Key-AppID'])->required();
                $rule[] = Form::input('token', '代码上传密钥', $row['token'] ?? '')->effect(['help' => '在抖音开放平台-控制台-小程序-开发-开发配置-秘钥设置-小程序代码上传秘钥'])->required();
                $rule[] = Form::input('email', '登录邮箱', $row['email'] ?? '')->effect(['help' => '抖音开放平台登录邮箱'])->required();
                $rule[] = Form::input('password', '登录密码', $row['password'] ?? '')->effect(['help' => '抖音开放平台登录密码'])->required();
                $rule[] = Form::input('domain', '自定义域名', $row['domain'] ?? '')
                    ->effect(['help' => '设置自定义的接口域名地址，需要为https://开头，结尾不要有/，如：https://www.xxx.com，不填则默认使用上传审核的时候获取的当前域名']);
            } else {
                return $this->error("当前无配置项");
            }
            $form->setTitle("上传配置")->setRule($rule);
            return $this->success("", Form::getFormData($form));
        }
    }

    public function server_config()
    {
        $appid = $this->request->param('appid', 0);
        $platform_app = (new PlatformApp())->where(['id' => $appid])->find();
        if (!$platform_app) {
            return $this->error('请先设置默认小程序');
        }
        if ($this->request->isPost()) {
            $formData = $this->request->param('formData', []);
            $platform_app->server_config = $formData;
            $platform_app->save();
            return $this->success("修改成功");
        } else {
            $rule = array();
            //创建表单
            $row = $platform_app['server_config'] ?? [];
            $form = Form::createForm("/adminapi/platform/min_app/setting/server_config?appid=" . $appid)->setMethod("post");
            //新增表单
            if ($platform_app['app_type'] == 'dy') {
                // 查询是否存在服务商app
                $min_app_open = (new PlatformAppOpen())->where(['addon_name' => $platform_app['addon_name'], 'type' => 'dy'])->find();
                $manual_rules = [
                    Form::input('appid', 'AppId', $row['appid'] ?? '')->effect(['help' => '填写小程序的AppID'])->required(),
                    Form::input('secret', 'AppSecret', $row['secret'] ?? '')->effect(['help' => '填写小程序的AppSecret,位置在：开发-开发配置-AppSecret'])->required(),
                ];

                $open_rules = [
                    Form::dkDouyinAppOpen('authorizer_appid', "扫码授权", $row['authorizer_appid'] ?? '')
                        ->effect(['help' => '点击按钮跳转到授权地址，确认授权后请勿点击返回控制台，等待自动跳转']),
                ];
                $auth_type = $min_app_open['config']['auth_type'] ?? 'manual';

                if ($auth_type == 'auto') {
                    //自由选择授权
                    $rule[] = Form::radio('auth_type', '授权方式', $row['auth_type'] ?? 0)
                        ->options([
                            ['label' => '手动配置', 'value' => 0],
                            ['label' => '服务商授权', 'value' => 1],
                        ])
                        ->effect(['help' => '设置小程序配置方式，可以选择手动配置或者服务商直接授权'])
                        ->appendControl(0, $manual_rules)
                        ->appendControl(1, $open_rules);
                } elseif ($auth_type == 'open') {
                    //扫码授权
                    $rule = array_merge($rule, $open_rules);
                } else {
                    $rule = array_merge($rule, $manual_rules);
                }
            }elseif($platform_app['app_type'] == 'wx'){
//                $min_app_open = (new PlatformAppOpen())->where(['addon_name' => $platform_app['addon_name'], 'type' => 'wx'])->find();
                $manual_rules = [
                    Form::input('appid', 'AppID', $row['appid'] ?? '')->effect(['help' => '填写小程序的AppID，位置在：管理-开发管理-开发设置-AppID(小程序ID)'])->required(),
                    Form::input('secret', 'AppSecret', $row['secret'] ?? '')->effect(['help' => '填写小程序的AppSecret，位置在：管理-开发管理-开发设置-AppSecret(小程序密钥)'])->required(),
                ];
                $rule = array_merge($rule, $manual_rules);
            } else {
                return $this->error("当前无配置项");
            }
            $form->setTitle("上传配置")->setRule($rule);
            return $this->success("", Form::getFormData($form), $row);
        }
    }
}
